package com.weixin.mw.itcar.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;


public class BaseAction extends ActionSupport implements ServletRequestAware,ServletResponseAware {
	private static final long serialVersionUID = -6597958209900145848L;
	protected Log logger = LogFactory.getLog(this.getClass());
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	private String callback;



	/**
	 * 检查权限用户
	 * @param userNick 用户昵称
	 * @param users 权限用户集合
	 * @return
	 */
	protected boolean checkUser(String userNick,String[] users){
		
		if(users == null || userNick == null || userNick.length() == 0) return false;
		
		for(String nick : users){
			if(nick.equals(userNick)) return true;
		}
		
		return false;
	}
	
	/**
	 * 检查活动时间
	 * @param start 开始时间
	 * @param end 结束时间
	 * @return
	 */
	protected boolean checkDate(Date start, Date end){
		
		Date now = new Date();
		
		if(start != null && now.before(start)) return false;
		
		return now.before(end);
	}
	
	/**
	 * 检查活动时间
	 * @param end
	 * @return
	 */
	protected boolean checkDate(Date end){
		
		return checkDate(null, end);
	}
	
	/**
	 * 下载文件
	 * @param bytes 文件字节数组
	 * @param sufferName 文件扩展名
	 * @param fileName 文件名
	 * @throws IOException
	 */
	protected void download(byte[] bytes, String suffixName, String fileName) throws IOException{
		response.reset();
		response.setContentType("application/" + suffixName);
		String name =  fileName + "." + suffixName;
		name.replaceAll(" ", "_");
		name = new String(name.getBytes("GBK"),"ISO8859_1");
	    response.setHeader("Content-Disposition", "attachment;" + "filename=" + name);
	    
	    OutputStream output = response.getOutputStream();
		output.write(bytes);
		
		output.flush();
		output.close();
        response.flushBuffer();
	}
	
	/**
     * 淘宝用户ID的编码转码
     * @return
     */
    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }
    
    public void printJSON(String str) {
    	response.setContentType("application/json; charset=utf-8");
    	try {
			response.getWriter().print(str);
		} catch (IOException e) {
			logger.error("BaseAction.printJSON", e);
		}
    }
    
    /**
     * 返回jsonp格式数据
     * @param str 数据
     * @param callback 回调名
     */
    public void printJSONP(String str, String callback) {

		response.setContentType("application/json; charset=utf-8");
		
    	try {
    		PrintWriter printWriter = response.getWriter();
    		if(printWriter == null){
    			logger.error("输出流为空");
    		}
    		if(callback == null || callback.length() == 0){
    			printWriter.print(str);
    		}else{
    			printWriter.print(callback + "(" + str + ")");
    		}
		} catch (Exception e) {
			logger.error("BaseAction.printJSONP", e);
		}
    }
    
    /**
     * 返回jsonp格式数据
     * @param str 数据
     */
    public void printJSONP(String str){

		printJSONP(str, this.callback);
    }
    
    public void print(String str) {
    	response.setContentType("text/html; charset=utf-8");
    	try {
			response.getWriter().print(str);
		} catch (IOException e) {
			logger.error("BaseAction.print", e);
		}
    }
    
    public static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if(pos == -1) {
        	return null;
        }
        return fileName.substring(pos);
    } 

	@Override
	public void setServletResponse(HttpServletResponse res) {
		this.response = res;
	}

	public void setCallback(String callback) {
		this.callback = callback;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}
}
